import { Response, NextFunction } from 'express';
import type { Request  } from 'express';
import { verifyToken } from '../utils/jwt';
import prisma from '../lib/prisma';

// 验证JWT令牌中间件
export const authenticate = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const token = req.cookies.token;

    if (!token) {
      return res.status(401).json({ success: false, message: '未提供认证令牌' });
    }

    const decoded = verifyToken(token);
    console.log(decoded, "decoded");
    if (!decoded) {
      return res.status(401).json({ message: '无效或过期的令牌' });
    }

    // 设置用户信息
    req.user = {
      id: decoded.id,
      username: decoded.username,
      email: decoded.email,
      businessLine: decoded.businessLine,
      roles: decoded.roles,
    };

    // 设置角色信息到 req.roles
    req.roles = decoded.roles;

    console.log(req.user, "req.user");
    console.log(req.roles, "req.roles");

    // 获取用户角色
    const user = await prisma.user.findUnique({
      where: { id: decoded.id },
    });
    if (!user) {
      return res.status(401).json({ message: '用户不存在' });
    }

    next();
  } catch (error) {
    console.error('认证过程中出错:', error);
    res.status(401).json({ message: '认证失败' });
  }
};

// 检查用户是否具有特定角色权限的中间件
export const authorize = (allowedRoles: string[]) => {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!req.user || !req.roles) {
      return res.status(401).json({ message: '请先登录' });
    }

    const hasAuthorizedRole = req.roles.some((role: string) => allowedRoles.includes(role));

    if (!hasAuthorizedRole) {
      return res.status(403).json({ message: '没有访问权限' });
    }

    next();
  };
}; 